const useRouteMenu = (menus: any) => {
    const route = useRoute();
    const router = useRouter();

    // 默认展开菜单
    const defaultOpenKeys = computed((): [] | string[] => {
        // return menus.map((menu: any) => menu.path);
        return menus.filter((menu: any) => menu.meta.defaultOpen).map((menu: any) => menu.path);
    });

    const parentRoute = computed(() => {
        return route.matched.length > 1 ? route.matched[route.matched.length - 2] : null
    });

    // 选中菜单
    const selectedKeys = computed((): [] | string[] => {
        const path = router.currentRoute.value.path;
        const menu = menus.filter((menu: any) => menu.path === path)
        if (menu && menu.length > 0) {
            return [menu[0].path];
        }
        console.log("parentRoute", parentRoute.value);
        if (parentRoute.value) {
            return [parentRoute.value.path];
        }
        return [];
    });

    // 点击菜单
    const onClickMenuItem = (key: string) => {
        const menu = getMatchedMenu(menus, key);
        if (!menu) {
            return;
        }
        logger("点击菜单", menu)
        if (menu.meta.outerLink) {
            window.open(menu.meta.outerLink, '_blank');
            return;
        }

        router.push(menu.path);
    }

    const getMatchedMenu = (menus: any[], path: string): any => {
        let matchedMenu
        for (const menu of menus) {
            if (menu.path === path) {
                logger("菜单匹配成功", menu)
                return menu

            } else if (menu.children) {
                logger("子菜单匹配", menu.children)
                matchedMenu = getMatchedMenu(menu.children, path)
                if (matchedMenu) {
                    return matchedMenu
                }
            }
        }
        return matchedMenu
    }

    return { defaultOpenKeys, selectedKeys, onClickMenuItem, getMatchedMenu };
};

export default useRouteMenu;